﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using BrainTechLLC.Silverlight.InputControls;
using System.Globalization;

namespace BrainTechLLC.Silverlight.InputControls2
{    
    /// <summary>
    /// The dumping ground for functionality that existed in InputControl and GridInputControl base classes.
    /// Instead of using a base class, we use composition and include an instance of the below class as a member of each input control.
    /// </summary>
    public class NonInheritedBaseInputClass
    {        
        public string GetValueFromDropdown(ComboBox cboDropdown, List<KeyValuePair<string, int>> ListItems)
        {
            if (cboDropdown.SelectedItem == null || ListItems == null)
                return "-1";

            for (int n = 0; n < ListItems.Count; n++)
            {
                if (ListItems[n].Key.Equals(cboDropdown.SelectedItem))
                    return ListItems[n].Value.ToString();
            }

            return "-1";
        }

        public void SetInputControlBehavior(FilteredTextBox txtEditor, DataType dataType, TextFormat format)
        {
            switch (dataType)
            {
                case DataType.INTEGER:
                    txtEditor.ValidatingType = typeof(int);
                    break;
                case DataType.CURRENCY:
                    txtEditor.ValidatingType = typeof(decimal);
                    break;
                case DataType.PERCENTAGE:
                    txtEditor.ValidatingType = typeof(decimal);
                    break;
                case DataType.DOUBLE:
                    txtEditor.ValidatingType = typeof(double);
                    break;
                case DataType.DATE:
                    txtEditor.Mask = "00/00/0000";
                    txtEditor.ValidatingType = typeof(DateTime);
                    break;
                case DataType.STRING:
                    SetStringBehavior(txtEditor, format);
                    break;
            }
        }

        protected void SetStringBehavior(FilteredTextBox txtEditor, TextFormat format)
        {
            switch (format)
            {
                case TextFormat.PHONE:
                    txtEditor.Mask = "0000000000";
                    break;
                case TextFormat.YYYY:
                    txtEditor.Mask = "0000";
                    break;
                case TextFormat.ZIP:
                    txtEditor.Mask = "00000";
                    break;
                case TextFormat.ZIP4:
                    txtEditor.Mask = "0000";
                    break;
                case TextFormat.EMAIL:
                    break;
            }
        }

        public void SetTooltipBase(IInputControl2 inputControl, string hardValidationFailureMessage, string baseHelpText)
        {
            if (!string.IsNullOrEmpty(hardValidationFailureMessage))
            {
                // Invalid value in field.  Set tooltip to help text plus error message
                PrivateSetTooltipText(inputControl, baseHelpText + Environment.NewLine + Environment.NewLine + hardValidationFailureMessage);
            }
            else
            {
                // Validation rule failure - set tooltip to text describing the failure
                string errorTitle = string.Empty;
                string errorText = string.Empty;

                //ReadLatestErrorTextAndTitleBase(out errorText, out errorTitle, true);

                if (string.IsNullOrEmpty(errorText))
                {
                    PrivateSetTooltipText(inputControl, baseHelpText);
                }
                else
                {
                    string fullTooltipText = baseHelpText + Environment.NewLine + Environment.NewLine + errorTitle + errorText;
                    PrivateSetTooltipText(inputControl, fullTooltipText);
                }
            }
        }

        public void PrivateSetTooltipText(IInputControl2 inputControl, string text)
        {
            if (inputControl.PrimaryInputControl != null)
            {
                ToolTip tooltip = ToolTipService.GetToolTip(inputControl.PrimaryInputControl as Control) as ToolTip;

                if (tooltip == null)
                {
                    tooltip = new ToolTip() { Content = text };

                    if (inputControl.ImageIcon != null)
                        ToolTipService.SetToolTip((Image)inputControl.ImageIcon, tooltip);

                    if (inputControl.PrimaryInputControl != null)
                    {
                        ToolTipService.SetToolTip(inputControl.PrimaryInputControl as Control, tooltip);
                    }
                }

                if (tooltip.Content == null || !tooltip.Content.ToString().Equals(text))
                {
                    tooltip.Content = text;
                }
            }
        }

        /// <summary>
        /// Given the latest failed validation rules, outputs a meaningful error message and title
        /// </summary>
        //public void ReadLatestErrorTextAndTitleBase(out string errorTextString, out string errorTitleString, bool forceBypassQuestionsToErrors)
        //{
        //    errorTextString = string.Empty;
        //    errorTitleString = string.Empty;
        //}

        public static void SetBackgroundColorAndImage(ReviewState2 controlState, IInputControl2 inputControl)
        {
            Image img = ((Image)inputControl.ImageIcon);
            ImageSource imgSource = null;// HEREHERE
            Brush brush = inputControl.BackgroundForNotSet;
            Brush notesBrush = null;

            switch (controlState)
            {
                case ReviewState2.Valid:
                    brush = inputControl.BackgroundForValid;
                    break;

                case ReviewState2.None:
                    brush = inputControl.BackgroundForNone;
                    break;

                case ReviewState2.Info:
                    brush = inputControl.BackgroundForInfo;
                    break;

                case ReviewState2.Invalid:
                    brush = inputControl.BackgroundForInvalid;
                    break;

                case ReviewState2.Warning:
                    {
                        if (!string.IsNullOrEmpty(inputControl.Value))
                        {
                            brush = inputControl.BackgroundForWarning;
                            notesBrush = inputControl.BackgroundForWarning;
                        }
                    }
                    break;
            }

            if (img != null && !img.Source.Equals(imgSource))
                img.Source = imgSource;

            Control c = inputControl.PrimaryInputControl as Control;

            if (c.Background != null && !c.Background.Equals(brush))
                c.Background = brush;
        }

        public virtual void SetControlState(ReviewState2 controlState, IInputControl2 inputControl)
        {
            if (inputControl.ControlReviewState != controlState)
            {
                SetBackgroundColorAndImage(controlState, inputControl);
                inputControl.ControlReviewState = controlState;
            }
        }

        public void SetReviewStateForFailedRule(ValidationType failedRuleType, IInputControl2 parent)
        {
            switch (failedRuleType)
            {
                case ValidationType.SOFT:
                    parent.ControlReviewState = ReviewState2.Warning;
                    break;

                case ValidationType.REQUIRED:
                    parent.ControlReviewState = ReviewState2.Invalid;
                    break;
            }
        }
        public static bool ValidateValue(DataType dataType, string value)
        {
            switch (dataType)
            {
                case DataType.CURRENCY:
                    return value.IsValidMoneyAmount(ReturnIfEmpty.True);

                case DataType.DATE:
                    return value.IsValidDate(true, ReturnIfEmpty.True);

                case DataType.DOUBLE:
                    return value.IsNumeric();

                case DataType.INTEGER:
                    return value.IsValidInteger(ReturnIfEmpty.True);

                case DataType.PERCENTAGE:
                    return value.IsValidPercentage(ReturnIfEmpty.True);
            }

            return true;
        }



        public string ValidateContents(IInputControl2 inputControl, DataType dataType, TextFormat format, ValidationType validationType)
        {
            string value = inputControl.Value;

            bool valid = !(validationType == ValidationType.REQUIRED && string.IsNullOrEmpty(value));

            if (!valid)
                return "This value cannot be left blank.";

            if (valid && !string.IsNullOrEmpty(value))
            {
                // Perform datatype checking
                valid = dataType.ValidateValue(value);

                if (!valid && dataType == DataType.INTEGER && value == "-1")
                    valid = true;

                if (!valid)
                    return "Input was not in the expected format.";
            }

            if (valid && !string.IsNullOrEmpty(value))
            {
                // Regular expression checks
                string regEx = RegExFactory.CreateRegEx(format);

                if (!string.IsNullOrEmpty(regEx))
                    valid = Regex.IsMatch(value, regEx);

                if (!valid)
                    return "Input was not in the expected format.";
            }

            if (!valid)
                inputControl.SetControlState(ReviewState2.Invalid);

            return valid ? "" : "Error";
        }
    }
}
